package xyz.riceball.usercore.websocket.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.riceball.framework.core.annotation.RbSysRequest;
import xyz.riceball.usercore.websocket.WebsocketServer;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *
 * </p>
 *
 * @author xiaovcloud
 * @since 2022/5/9 21:43
 */
@Service
@RbSysRequest
@ServerEndpoint("/rb/api/usercore/websocket/{userId}")
@Slf4j
public class UserWebsocketServer implements WebsocketServer {

    //在线的人数
    private static final AtomicInteger online = new AtomicInteger();

    //存储连接用户的session
    private static final ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     * 发送消息方法
     *
     * @param session 客户端与socket建立的会话
     * @param message 消息
     * @throws IOException
     */
    public void sendMessage(Session session, Object message) throws IOException, EncodeException {
        if (session != null) {
            session.getBasicRemote().sendObject(message);
        }
    }

    /**
     * 连接建立成功调用
     *
     * @param session 客户端与socket建立的会话
     * @param userId  客户端的userName
     */
    @OnOpen
    @Override
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        sessionPools.put(userId, session);
        addOnlineCount();
        log.info("在线人数：{}", online);
        //用户上线逻辑处理
    }

    /**
     * 关闭连接时调用
     *
     * @param userId 关闭连接的客户端的姓名
     */
    @OnClose
    @Override
    public void onClose(@PathParam(value = "userId") String userId) {
        sessionPools.remove(userId);
        subOnlineCount();
        log.info("在线人数：{}", online);
        //用户下线处理
    }

    /**
     * 收到客户端消息时触发（群发）
     *
     * @param message 消息
     */
    @OnMessage
    @Override
    public void onMessage(String message) throws IOException {
        log.info("usercore发送全局消息:{}", message);
        for (Session session : sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时候
     *
     * @param session   session
     * @param throwable throwable
     */
    @OnError
    @Override
    public void onError(Session session, Throwable throwable) {
        log.error("websocket发生错误", throwable);
        throwable.printStackTrace();
    }

    /**
     * 给指定用户发送消息
     *
     * @param userId  用户名
     * @param message 消息
     */
    public void sendInfo(String userId, Object message) {
        Session session = sessionPools.get(userId);
        log.info("usercore向用户：（{}）发送消息:{}", userId, message);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addOnlineCount() {
        online.incrementAndGet();
    }

    public static void subOnlineCount() {
        online.decrementAndGet();
    }
}
